#include "/home/cdd/day5/func.h"
#define NUM 10000000
typedef struct shareResource_s{
    int count;
    pthread_mutex_t mutex;
} shareResource_t;
// 线程函数
void* increment_variable(void* arg) {
    shareResource_t * pshareRes = (shareResource_t *)arg;
    for(int i = 0; i < NUM; ++i){
        pthread_mutex_lock(&pshareRes->mutex);
        ++pshareRes->count;
        pthread_mutex_unlock(&pshareRes->mutex);
    }
    pthread_exit(NULL);
}
int main() {
    pthread_t thread1, thread2;
    shareResource_t shareRes;//在main的栈帧中，申请了内存
    shareRes.count = 0;
    struct timeval start_time, end_time;
    long total_time;
    // 初始化互斥锁
    if (pthread_mutex_init(&shareRes.mutex, NULL)!= 0) {
        perror("Mutex initialization failed");
        return 1;
    }
    // 获取开始时间
    gettimeofday(&start_time, NULL);
    // 创建线程
    if (pthread_create(&thread1, NULL, increment_variable, &shareRes)!= 0) {
        perror("Thread 1 creation failed");
        return 1;
    }
    if (pthread_create(&thread2, NULL, increment_variable, &shareRes)!= 0) {
        perror("Thread 2 creation failed");
        return 1;
    }
    // 等待线程结束
    if (pthread_join(thread1, NULL)!= 0) {
        perror("Thread 1 join failed");
        return 1;
    }
    if (pthread_join(thread2, NULL)!= 0) {
        perror("Thread 2 join failed");
        return 1;
    }
    // 获取结束时间
    gettimeofday(&end_time, NULL);
    // 计算总时间（单位：微秒）
    total_time = (end_time.tv_sec - start_time.tv_sec) * 1000000 + (end_time.tv_usec - start_time.tv_usec);
    // 销毁互斥锁
    pthread_mutex_destroy(&shareRes.mutex);
    printf("Final value of global variable: %d\n", shareRes.count);
    printf("Total time taken for locking and unlocking: %ld microseconds\n", total_time);
    return 0;
}
